package cn.exrick.controller;


import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import cn.exrick.common.alipay.AlipayService;
import cn.exrick.pojo.TbMemberVipRule;
import cn.exrick.service.MemberVipRuleService;
import cn.exrick.utils.IDUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.gson.Gson;

import cn.exrick.common.exception.NeedLoginException;
import cn.exrick.common.exception.XmallException;
import cn.exrick.common.jedis.JedisClient;
import cn.exrick.common.zhima.ZhimaCertificatiionService;
import cn.exrick.pojo.common.Result;
import cn.exrick.pojo.front.GeetInit;
import cn.exrick.pojo.front.Member;
import cn.exrick.pojo.front.ZhimaResult;
import cn.exrick.service.LoginService;
import cn.exrick.service.MemberFrontService;
import cn.exrick.service.RegisterService;
import cn.exrick.utils.CertNumUtil;
import cn.exrick.utils.GeetestLib;
import cn.exrick.utils.ResultUtil;
import cn.exrick.utils.enums.MemberCertifyEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@RestController
@Api(description = "会员注册登录")
public class MemberFrontController {

    private final static Logger log = LoggerFactory.getLogger(MemberFrontController.class);

    @Autowired
    private LoginService loginService;
    @Autowired
    private RegisterService registerService;
    @Autowired
    private MemberFrontService memberFrontService;
    @Autowired
    private JedisClient jedisClient;
    @Autowired
    private ZhimaCertificatiionService zhimaCertificatiionService;
    @Autowired
    private MemberVipRuleService memberVipRuleService;
    @Autowired
    private AlipayService alipayService;

    @RequestMapping(value = "/member/geetestInit", method = RequestMethod.GET)
    @ApiOperation(value = "极验初始化")
    public String geetesrInit(HttpServletRequest request) {

        GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);

        String resStr = "{}";

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();

        //进行验证预处理
        int gtServerStatus = gtSdk.preProcess(param);

        //将服务器状态设置到redis中
        //request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
        String key = UUID.randomUUID().toString();
        jedisClient.set(key, gtServerStatus + "");
        jedisClient.expire(key, 360);

        resStr = gtSdk.getResponseStr();
        GeetInit geetInit = new Gson().fromJson(resStr, GeetInit.class);
        geetInit.setStatusKey(key);
        return new Gson().toJson(geetInit);
    }

    @RequestMapping(value = "/member/login", method = RequestMethod.POST)
    @ApiOperation(value = "用户登录")
    public Result<Member> login(String phone, String userPwd) {
        // 验证成功
        Member member = loginService.userLogin(phone, userPwd);
        member.setShareUrl("/dist/index.html#/downLoad3");
        return new ResultUtil<Member>().setData(member);
    }

    @RequestMapping(value = "/member/checkLogin", method = RequestMethod.GET)
    @ApiOperation(value = "判断用户是否登录")
    public Result<Member> checkLogin(@RequestParam(defaultValue = "") String token) {

        Member member = loginService.getUserByToken(token);
        return new ResultUtil<Member>().setData(member);
    }

    @RequestMapping(value = "/member/loginOut", method = RequestMethod.GET)
    @ApiOperation(value = "退出登录")
    public Result<Object> logout(@RequestParam(defaultValue = "") String token) {

        loginService.logout(token);
        return new ResultUtil<Object>().setData(null);
    }

    /**
     * 极验验证码验证
     *
     * @param challenge
     * @param validate
     * @param seccode
     * @param statusKey
     * @return
     */
    public boolean checkGeetestLib(String challenge, String validate, String seccode, String statusKey) {
        //极验验证
        GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);

        //从redis中获取gt-server状态
        //int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
        int gt_server_status_code = Integer.parseInt(jedisClient.get(statusKey));

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();

        int gtResult = 0;

        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println(gtResult);
        }
        if (gtResult == 1) {
            return true;
        } else {
            return false;
        }
    }

    @RequestMapping(value = "/member/register", method = RequestMethod.POST)
    @ApiOperation(value = "用户注册")
    public Result<Object> register(String phone, String userName, String userPwd, String code, String city) {
        // 验证成功
        int result = registerService.register(phone, userName, userPwd, code, city);
        if (result == 0) {
            throw new XmallException("该用户名已被注册");
        } else if (result == -1) {
            throw new XmallException("手机号用户名密码不能为空");
        }
        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/changePassword", method = RequestMethod.POST)
    @ApiOperation(value = "用户修改密码")
    public Result<Object> imgaeUpload(String phone, String code, String newPassword) {
        Member member = loginService.findMemberByPhone(phone);
        if (member == null) {
            throw new XmallException("账号不存在");
        }
        if (!SMSController.checkCode(phone, code)) {
            throw new XmallException("验证码错误");
        }

        if (memberFrontService.changePassword(member.getId(), newPassword)) {
            return new ResultUtil<Object>().setData(true);
        } else {
            throw new XmallException("修改失败");
        }
    }

    @RequestMapping(value = "/member/changeInfo", method = RequestMethod.POST)
    @ApiOperation(value = "用户修改信息")
    public Result<Object> changeInfo(String userName, String imageUrl, String city, String busScope, String busScopeImage, String token) {
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }
        String imgPath = memberFrontService.changeInfo(token, userName, imageUrl, city, busScope, busScopeImage);
        return new ResultUtil<Object>().setData(true);
    }
    
	@RequestMapping(value = "/member/zhima/init", method = RequestMethod.POST)
	@ApiOperation(value = "用户实名认证-初始化接口")
	public Result<ZhimaResult> zhimaCertificationInit(String token, String certUserName, String certNum) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		if(member.getCertify() == 1) {
			throw new XmallException("已实名认证");
		}
		if (StringUtils.isEmpty(certUserName)) {
			throw new XmallException("请输入姓名");
		}
		if (StringUtils.isEmpty(certNum)) {
			throw new XmallException("请输入身份证号码");
		}
		if (!CertNumUtil.validator(certNum)) {
			throw new XmallException("身份证号码不对");
		}
		ZhimaResult result = zhimaCertificatiionService.init(certUserName, certNum);
		if(result.isSuccess()) {
			memberFrontService.updateMemRealInfo(member.getId(), certUserName, certNum);
		}
		return new ResultUtil<ZhimaResult>().setData(result);
	}
	
	@RequestMapping(value = "/member/zhima/certify", method = RequestMethod.POST)
	@ApiOperation(value = "用户实名认证-开始认证接口")
	public Result<ZhimaResult> zhimaCertificationCertify(String token, String initSuccessNo) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		if(member.getCertify() == 1) {
			throw new XmallException("已实名认证");
		}
		if (StringUtils.isEmpty(initSuccessNo)) {
			throw new XmallException("初始化认证失败");
		}
		ZhimaResult result = zhimaCertificatiionService.certify(initSuccessNo);
		return new ResultUtil<ZhimaResult>().setData(result);
	}
	
	@RequestMapping(value = "/member/zhima/query", method = RequestMethod.POST)
	@ApiOperation(value = "用户实名认证-查询认证结果接口")
	public Result<ZhimaResult> zhimaCertificationQuery(String token, String initSuccessNo) {
		Member member = loginService.getUserByToken(token);
		if (member == null) {
			throw new NeedLoginException();
		}
		if (StringUtils.isEmpty(initSuccessNo)) {
			throw new XmallException("初始化认证失败");
		}
		ZhimaResult result = zhimaCertificatiionService.query(initSuccessNo);
		if(result.isSuccess()) {
			memberFrontService.updateMemCertify(member.getId(),MemberCertifyEnum.CERTIFYSUCCESS.getId());
		}
		return new ResultUtil<ZhimaResult>().setData(result);
	}

    @RequestMapping(value = "/member/zhima/pay", method = RequestMethod.POST)
    @ApiOperation(value = "用户实名认证-支付认证费用")
    public Result<Object> memberZhimaPay(String token) {
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }
        if (member.getCertify() == 1) {
            throw new XmallException("会员已通过认证，发起支付失败");
        }

        String packageParams = "type=memberCertify&memberId=" + member.getId();
        String result = alipayService.sendAppPay(String.valueOf(IDUtil.getRandomId()), "手机联盟会员认证", "芝麻认证费用", packageParams,
                new BigDecimal("1"));

        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/vip/ruleList", method = RequestMethod.POST)
    @ApiOperation(value = "开通会员-获取套餐列表")
    public Result<List<TbMemberVipRule>> memberVipRuleList(String token) {
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }
        List<TbMemberVipRule> list = memberVipRuleService.queryAll();
        return new ResultUtil<List<TbMemberVipRule>>().setData(list);
    }

    @RequestMapping(value = "/member/vip/pay", method = RequestMethod.POST)
    @ApiOperation(value = "开通会员-支付套餐费用")
    public Result<Object> memberVipRulePay(String token, Integer ruleId) {
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }
        if (member.getCertify() != 1) {
            throw new NeedLoginException("未认证，无法开通会员");
        }
        TbMemberVipRule tbMemberVipRule = memberVipRuleService.queryById(ruleId);
        if (tbMemberVipRule == null) {
            throw new XmallException("通过id获取会员套餐失败");
        }

        String packageParams = "type=memberVip&memberVipRuleId=" + ruleId + "&memberId=" + member.getId();
        String result = alipayService.sendAppPay(String.valueOf(IDUtil.getRandomId()), "手机联盟会员申请", tbMemberVipRule.getName(), packageParams,
                tbMemberVipRule.getPrice());

        return new ResultUtil<Object>().setData(result);
    }

    @RequestMapping(value = "/member/info", method = RequestMethod.POST)
    @ApiOperation(value = "获取会员信息")
    public Result<Member> memberInfo(String token) {
        Member member = loginService.getUserByToken(token);
        if (member == null) {
            throw new NeedLoginException();
        }
        member = loginService.findMemberByPhone(member.getPhone());
        return new ResultUtil<Member>().setData(member);
    }

}
